<template>
  <view class="my-coupon">
    <u-line color="#f6f6f6"></u-line>
    <!-- 顶部tab -->
    <view class="tab-box">
    	<u-tabs-swiper 
        ref="uTabs" 
        :list="list" 
        :current="current" 
        @change="tabsChange" 
        :is-scroll="false"
        active-color="#333"
        inactive-color="#666"
        swiperWidth="750" 
        bar-width="80"
        :bar-style="barActiveStyle"
      ></u-tabs-swiper>
    </view>
    
    <view class="content">
      <swiper class="swiper" :current="swiperCurrent" @transition="transition" @animationfinish="animationfinish">
      	<swiper-item class="swiper-item" v-for="(item, index) in result" :key="index">
      		<scroll-view class="scroll-view" scroll-y @scrolltolower="onLoadmore">
      	    <u-empty mode="coupon" v-if="item.data.length <= 0 && item.isEnd"></u-empty>
      	    <view style="overflow: hidden;" v-else>
      	      <view v-for="(i, k) in item.data" :key="k">
      	        <coupon-item @click="jumpPage" :item="i" :type="result[index].couponClass" v-if="!i.is_Package" />
      	        <set-meal-item @click="jumpPage" :item="i" v-else />
      	      </view>
      	      
      	      <view class="loading-status"><u-loadmore :status="item.status" /></view>
      	    </view>
      		</scroll-view>
      	</swiper-item>
        
      </swiper>
    </view>
  </view>
</template>

<script>
import couponItem from './components/couponItem.vue' // 优惠券列表组件
import setMealItem from './components/setMealItem.vue' // 套餐列表组件
export default {
  components: {
    couponItem,
    setMealItem
  },
  data() {
    return {
      barActiveStyle: {
        'background': 'linear-gradient(0deg, #FBB000, #FFE23E)'
      }, // tab选中是下划线样式
      list: [{
        name: '全部'
      }, {
        name: '养车券'
      }, {
        name: '套餐卡'
      }], // tab数据列表
      current: 0, // tabs组件的current值
      swiperCurrent: 0 ,// swiper组件的current值
      result: [
        {
          couponClass: 5,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
        {
          couponClass: 2,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        },
        {
          couponClass: 4,
          PageIndex: 1,
          PageSize: 20,
          isEnd: false,
          loading: false,
          status: 'loading',
          data: []
        }
      ],
      from: '', // 页面来源 用于点击套餐判断，如果没有值就跳转详情页
      mobile: '' // 用户手机号
    }
  },
  computed: {
    // 订单信息
    orderinfo() {
      return this.$store.state.maintenanceOrder
    },
    maintenanceOrderInfo() {
      return this.$store.state.maintenanceOrderInfo
    }
  },
  onLoad(option) {
    // #ifdef H5
    if (this.orderinfo) {
      let maintenanceOrderInfo = sessionStorage.maintenanceOrderInfo ? JSON.parse(sessionStorage.maintenanceOrderInfo) : []
      this.$store.commit('maintenanceOrderInfo', maintenanceOrderInfo)
    }
    // #endif
    
    this.current = Number(option.status) || 0
    this.swiperCurrent = Number(option.status) || 0
    this.from = option.from || ''
    this.mobile = option.mobile || ''
    let userinfo = uni.getStorageSync('Ztc_C_USER_INFO')
    if(!this.mobile && userinfo) {
      this.mobile = userinfo.mobile
    }
    this.getList()
  },
  methods: {
    // 点击tan切换
    tabsChange(index) {
      this.swiperCurrent = index;
      this.getList()
    },
    transition(e) {
      let dx = e.detail.dx;
      this.$refs.uTabs.setDx(dx);
    },
    animationfinish(e) {
      let current = e.detail.current;
      this.$refs.uTabs.setFinishCurrent(current);
      this.swiperCurrent = current;
      this.current = current;
      this.getList()
    },
    // 禁用swiper滑动
    stopTouchMove() {
      return false
    },
    onLoadmore() {
      this.getList()
    },
    // 跳转页面
    jumpPage(data) {
      if(!data.is_Package && !this.from) {
        uni.navigateTo({
          url: `/pages_userModule/myCoupon/detail?id=${data.id}`
        })
        this.$store.commit('couponInfo', data)
      } else if(data.is_Package && !this.from) {
        uni.navigateTo({
          url: `/pages_userModule/myCoupon/setMealDetail?id=${data.id}`
        })
      } else {
        // 检测优惠券
        this.checkCoupon(data)
      }
    },
    // 计算总共有多少页
    pageCount (totalnum,limit){
      return totalnum > 0 ? ((totalnum < limit) ? 1 : ((totalnum % limit) ? (parseInt(totalnum / limit) + 1) : (totalnum / limit))) : 0
    },
    // 获取列表数据
    async getList(type) {
      let list = this.result[this.swiperCurrent]
      if (type) {
        list.PageIndex = 1
        list.isEnd = false
        list.loading = false
        list.status = 'loading'
      }
      if (list.loading || list.isEnd) {
        return false
      }
      list.loading = true
      this.$set(this.result, this.swiperCurrent, list)
      try{
        let res = await this.$api.user.GetCouponList({
          coupon_class: list.couponClass,
          pageIndex: list.PageIndex,
          pageSize: list.PageSize,
          mobile: this.mobile
        })
        
        let couponlist = res.data.list
        if (type) {
          list.data = []
        }
        
        if(couponlist.length <= 0 || list.PageIndex >= this.pageCount(res.data.total, list.PageSize)) {
          list.isEnd = true
          list.status = 'nomore'
        }
        
        if (couponlist.length > 0) {
          list.data = list.data.concat(couponlist)
          list.PageIndex = list.PageIndex + 1
        }
        list.loading = false
        this.$set(this.result, this.swiperCurrent, list)
      }catch(e){
        list.loading = false
        this.$set(this.result, this.swiperCurrent, list)
      }
      
    },
    // 检测优惠券
    checkCoupon1(data) {
      if(data.is_Package) {
        uni.navigateTo({
          url: `/pages_commodity/choosePackage/choosePackage?id=${data.id}&name=${encodeURIComponent(data.coupon_package_name)}`
        })
        return false;
      }
      if (!this.orderinfo) {
        let orderinfo = sessionStorage.maintenanceOrder ? JSON.parse(sessionStorage.maintenanceOrder) : []
        this.$store.commit('maintenanceOrder', orderinfo)
      }
      let params = {
        goodsList: [],
        serviceFeeList: [],
        discountTotalAmount: 0
      }
      this.orderinfo.goodsList.map(item => {
        item.maintenanceGoodsLists.map(i => {
          i.count = i.amount
          params.goodsList.push(i)
        })
      })
      this.orderinfo.serviceFeeList.map(item => {
        params.serviceFeeList.push(item)
      })
      if(data.is_Package) {
        params.selectedCouponId = data.id
      } else {
        params.selectedCouponDetailsId = data.cid
      }
      uni.showLoading({
        title: '加载中',
        mask: true
      })
      this.$api.maintenanceOrder.CheckCouponsByGoods(params).then(res => {
        uni.hideLoading()
        if(res.code === 200) {
          data.discountTotalAmount = -res.data.discountTotalAmount
          uni.$emit('changeCoupon', {
            data,
            goodsList: res.data.goodsList,
            discountTotalAmount: -res.data.discountTotalAmount
          })
          // uni.showToast({
          //   icon: 'none',
          //   title: '已到最大优惠金额，暂时无法使用'
          // })
          uni.navigateBack({
            delta: 1
          })
        } else {
          uni.showToast({
            icon: 'none',
            title: res.msg
          })
        }
      }).then(err => {
        uni.hideLoading()
      })
    },
    checkCoupon(data) {
      if(data.is_Package) {
        uni.navigateTo({
          url: `/pages_commodity/choosePackage/choosePackage?id=${data.id}&name=${encodeURIComponent(data.coupon_package_name)}`
        })
        return false;
      }
      if (!this.orderinfo) {
        let orderinfo = sessionStorage.maintenanceOrder ? JSON.parse(sessionStorage.maintenanceOrder) : []
        this.$store.commit('maintenanceOrder', orderinfo)
      }
      this.GetUsableCouponsByIdAndGoods(data.id)
    },
    async GetUsableCouponsByIdAndGoods(id) {
      let params = {
        goodsList: [],
        serviceFeeList: []
      }
      this.orderinfo.goodsList.map(item => {
        item.maintenanceGoodsLists.map(i => {
          params.goodsList.push({
            maintenance_Type_Id: i.maintenance_Type_Id,
            maintenance_Goods_Id: i.id,
            sale_Price: i.amount * i.sale_Price
          })
        })
      })
      this.orderinfo.serviceFeeList.map(item => {
        params.serviceFeeList.push({
          serviceId: item.serviceId,
          service_Calculate_Rule_id: item.service_Calculate_Rule_id,
          sale_Price: item.svcPrcTotal
        })
      })
      try {
        const res = await this.$api.maintenanceOrder.GetUsableCouponsByIdAndGoods({
          id: id,
          car_num: this.maintenanceOrderInfo.myLoveCar.car_Num,
          ...params
        })
        uni.hideLoading()
        if (res.code === 200) {
          let data = res.data
          let total = 0
          let arr = []
          let status = false
          data.groupList.map(item => {
            item.goodsServiceList.map(i => {
              if(i.isUsable) {
                total += Number(-i.discountAmount)
                res.data.coupon.coupon_Id = i.coupon_Id
                res.data.coupon.coupon_Details_Id = i.coupon_Details_Id
              }
              arr.push(i)
            })
          })
          status = arr.some(item => {
            return item.isUsable
          })
          if(status) {
            uni.$emit('changeCoupon', {
              data: res.data.coupon,
              discountTotalAmount: total
            })
            uni.navigateBack({
              delta: 1
            })
          } else{
            uni.showToast({
              icon: 'none',
              title: '对不起，无法使用该优惠券'
            })
          }
        } else {
          uni.showToast({
            icon: 'none',
            title: res.msg
          })
        }
      } catch (e) {
        uni.hideLoading()
      }
    }
  }
}
</script>

<style>
page{
  background-color: #f6f6f6;
}
</style>

<style lang="scss">
page{
  height: 100%;
}
.my-coupon{
  height: 100%;
  display: flex;
  flex-direction: column;
  .content{
    flex: 1;
    overflow: hidden;
  }
  .swiper, .swiper-item, .scroll-view{
    height: 100%;
  }
  .loading-status{
    padding: 40rpx 0;
  }
  .coupon-item:last-child{
    margin-bottom: 0 !important;
  }
}


</style>
